//
//  LoginViewController.m
//  jianpai
//
//  Created by yurui on 16/1/8.
//  Copyright © 2016年 yrapp. All rights reserved.
//

#import "LoginViewController.h"
#import "UMSocial.h"
#import "WXApi.h"
#import "RegistViewController.h"
#import "ForgetMMViewController.h"
#import "WXModel.h"
@interface LoginViewController ()<UITextFieldDelegate>
@property(nonatomic,strong) UIButton *backBt;//返回按钮
@property(nonatomic,strong) UIImageView *iconImageView;//头部试图
@property(nonatomic,strong) UILabel *phoneLabel;//账号
@property(nonatomic,strong) UITextField *phoneTF;//账号输入框
@property(nonatomic,strong) UILabel *mmLabel;//密码
@property(nonatomic,strong) UITextField *mmTF;//密码输入框
@property(nonatomic,strong) UIButton *loginBt;//登陆按钮
@property(nonatomic,strong) UIButton *forgetMM;//忘记密码按钮
@property(nonatomic,strong) UILabel *NoUserNameLabel;//
@property(nonatomic,strong) UIButton *phoneRegBt;// 手机注册按钮
@property(nonatomic,strong) AppDelegate *delegate;


@end

@implementation LoginViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kViewBackColor;
    self.title = @"登录";
    self.delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [self addSubViews];
    
}
// 添加子控件

- (void)addSubViews{
    

    UIView *backG = [[UIView alloc]initWithFrame:CGRectMake(0, 75, kWidth, 190)];
    backG.backgroundColor = kViewBackColor;
    [self.view addSubview:backG];
    // 账号输入框
    self.phoneTF = [[UITextField alloc]initWithFrame:CGRectMake(15,45, kWidth - 30, 40)];
    self.phoneTF.placeholder = @"手机号";
    self.phoneTF.backgroundColor = [UIColor whiteColor];
    self.phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    self.phoneTF.text = [kUserDefault objectForKey:@"phone"];
    self.phoneTF.clearButtonMode=UITextFieldViewModeWhileEditing;
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTF.font = [UIFont systemFontOfSize:15];
    [backG addSubview:_phoneTF];
    // 密码输入框
    self.mmTF = [[UITextField alloc]initWithFrame:CGRectMake(15, 100, kWidth - 30, 40)];
    self.mmTF.placeholder = @"登陆密码";
    self.mmTF.backgroundColor = [UIColor whiteColor];
    self.mmTF.borderStyle = UITextBorderStyleRoundedRect;
    self.mmTF.font = [UIFont systemFontOfSize:15];
    self.mmTF.secureTextEntry = YES;
    self.mmTF.clearButtonMode=UITextFieldViewModeWhileEditing;
    self.mmTF.delegate = self;
    [self.mmTF addTarget:self action:@selector(diDone:) forControlEvents:UIControlEventEditingChanged];
    
    [backG addSubview:_mmTF];
    
    // 登陆按钮
    self.loginBt = [[UIButton alloc]initWithFrame:CGRectMake(15, 260, kWidth - 30, 35)];
    _loginBt.backgroundColor = kBtColor;
    //self.loginBt.enabled = NO;
    self.loginBt.layer.cornerRadius = 5;
    [_loginBt setTitle:@"登 陆" forState:UIControlStateNormal];
    _loginBt.titleLabel.font = [UIFont systemFontOfSize:15];
    [_loginBt addTarget:self action:@selector(loginInAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBt];
    
    // 忘记密码
    self.forgetMM = [UIButton buttonWithType:UIButtonTypeSystem];
    self.forgetMM.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.forgetMM setTitle:@"忘记密码？" forState:UIControlStateNormal];
    self.forgetMM.tintColor = kBtColor;
    _forgetMM.frame = CGRectMake(kWidth / 2 + 5, 320, 65, 20);
    [_forgetMM addTarget:self action:@selector(goToForgetVC:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_forgetMM];
    //分割线
    UIView *fg = [[UIView alloc]initWithFrame:CGRectMake(kWidth / 2 - 0.5, 325, 1, 10)];
    fg.backgroundColor = [UIColor grayColor];
    [self.view addSubview:fg];
    
    // 手机注册按钮
    self.phoneRegBt = [UIButton buttonWithType:UIButtonTypeSystem];
    self.phoneRegBt.frame = CGRectMake(kWidth  / 2 - 70, 320, 70, 20);
    [self.phoneRegBt setTitle:@"手机注册" forState:UIControlStateNormal];
    self.phoneRegBt.titleLabel.font = [UIFont systemFontOfSize:13];
    self.phoneRegBt.tintColor = kBtColor;
    [self.phoneRegBt addTarget:self action:@selector(toRegisterControl:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_phoneRegBt];
    
    // 存放三方登陆按钮
    UIView *thirdLoginView = [[UIView alloc]initWithFrame:CGRectMake(0, 390, kWidth, 120)];
    thirdLoginView.backgroundColor = kViewBackColor;
    //thirdLoginView.userInteractionEnabled = YES;
    [self.view addSubview:thirdLoginView];
    // 其他登陆方式
    UILabel *styleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kWidth, 20)];
    styleLabel.text = @"其他登陆方式";
    styleLabel.textAlignment = NSTextAlignmentCenter;
    styleLabel.adjustsFontSizeToFitWidth = YES;
    styleLabel.font = [UIFont systemFontOfSize:13];
    styleLabel.textColor = [UIColor lightGrayColor];
    [thirdLoginView addSubview:styleLabel];
    // 微信登陆按钮
    UIButton *weChat = [UIButton buttonWithType:UIButtonTypeCustom];
    weChat.frame = CGRectMake(kWidth / 2 - 25, 35, 50, 50);
    [weChat setImage:[UIImage imageNamed:@"wxlogin.png"]forState:UIControlStateNormal];
    //weChat.imageView.image = [UIImage imageNamed:@"wxlogin.png"];
    weChat.layer.masksToBounds = YES;
    weChat.layer.cornerRadius = 25;
    [weChat addTarget:self action:@selector(thirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    [thirdLoginView addSubview:weChat];
    
}
// 三方微信登陆
- (void)thirdLogin:(UIButton *)sender{
    //微信登录
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];
            
            NSLog(@"username = %@\n, uid = %@\n, token = %@\n url = %@\n",snsAccount.userName,snsAccount.unionId,snsAccount.accessToken,snsAccount.iconURL);
           [kUserDefault setObject:snsAccount.unionId forKey:@"uid"];
        }
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToWechatSession completion:^(UMSocialResponseEntity *response) {
            NSLog(@"snsInformation is %@",response.data);
            WXModel *model = [[WXModel alloc]init];
            model.access_token = response.data[@"access_token"];
            model.gender = response.data[@"gender"];
            model.location = response.data[@"location"];
            model.profile_image_url = response.data[@"profile_image_url"];
            model.openid = response.data[@"openid"];
            model.screen_name = response.data[@"screen_name"];
            NSLog(@"model.access_token = %@\n model.gender =%@\n,model.location = %@\n,model.profile_image_url = %@\n,model.openid = %@\n,model.screen_name =%@",model.access_token,model.gender,model.location,model.profile_image_url,model.openid,model.screen_name);
            
        
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            NSString * uuid = [kUserDefault objectForKey:@"CFUUID"];
            NSLog(@"uuid = ----- %@",uuid);
            NSString *uid = [kUserDefault objectForKey:@"uid"];
            NSLog(@"uid = ****** %@",uid);
            NSLog(@"_______str = %@",_phoneTF.text);
           NSDictionary *parmeters = @{@"uuid":uuid,@"openid":model.openid,@"nickname":model.screen_name,@"userpic":model.profile_image_url,@"location":model.location,@"sex":model.gender,@"unionid":uid};
            [manager POST:@"http://wx1.01zg.com/plugins/app/chaozan/main.php?action=userlogin_weixin&sid=2216&uuid=&openid=&nickname=&userpic=&location=&sex=&unionid=" parameters:parmeters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"Success:%@",responseObject);
                NSString *mobile = responseObject[@"username"];
                NSLog(@"----mmmmmm = %@",mobile);
                [kUserDefault setObject:mobile forKey:@"phoneNum"];
                _WXname = response.data[@"screen_name"];
                [kUserDefault setObject:_WXname forKey:@"wxname"];
                [kUserDefault setObject:response.data[@"profile_image_url"] forKey:@"imageUrl"];
                _delegate.isLogin = 0;
                _delegate.isThirdLogin = 1;
                NSString *login = [NSString stringWithFormat:@"%d",self.delegate.isLogin];
                NSString *thirdLogin = [NSString stringWithFormat:@"%d",self.delegate.isThirdLogin];
                [kUserDefault setObject:login forKey:@"isLogin"];
                [kUserDefault setObject:thirdLogin forKey:@"thirdLogin"];
                
                [self.navigationController popToRootViewControllerAnimated:YES];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"erros: %@",error);
            }];
 
            
    
        }];
    });
}
//返回上一界面
- (void)backToBefor:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
// 登陆按钮实现
- (void)loginInAction:(UIButton *)sender{
    NSLog(@"登陆");
    if (_phoneTF.text.length < 11 || _phoneTF.text.length > 11) {
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入正确的手机号" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertV show];
    }else{
        // 保存账号
        [kUserDefault setObject:_phoneTF.text forKey:@"phone"];
        NSDictionary *parmeters = @{@"mobile":_phoneTF.text,@"userpass":_mmTF.text,@"ctype":@"1",@"uuid":@"123456"};
        [kUserDefault setObject:_phoneTF.text forKey:@"phoneNum"];
        [kUserDefault setObject:_mmTF.text forKey:@"mm"];
        NSLog(@"_phoneTF.text = %@",_phoneTF.text);
        
        [LORequestManger POST:@"http://wx1.01zg.com/plugins/app/chaozan/main.php?action=userlogin&sid=2216&mobile=&userpass=&crype=&uuid=" params:parmeters success:^(id response) {
            NSLog(@"Success:%@",response);
            NSString *errcode = [response objectForKey:@"errcode"];
            int err = [errcode intValue];
            if (err == 0) {
                NSLog(@"_phoneTF.text = %@",_phoneTF.text);
                _delegate.isLogin = 1;
                _delegate.isThirdLogin = 0;
                NSString *login = [NSString stringWithFormat:@"%d",self.delegate.isLogin];
                NSString *thirdLogin = [NSString stringWithFormat:@"%d",self.delegate.isThirdLogin];
                [kUserDefault setObject:login forKey:@"isLogin"];
                [kUserDefault setObject:thirdLogin forKey:@"thirdLogin"];
                
                [self.navigationController popViewControllerAnimated:YES];
            }else if (err == 25){
                UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该用户不存在" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertV show];
            }else if (err == 26){
                UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:@"密码错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertV show];
            }else if (err == 21){
                UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:@"密码不能小于6位" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertV show];
            }

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        NSLog(@"erros: %@",error);
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"账号或密码错误" delegate:self cancelButtonTitle:@"重新输入" otherButtonTitles:nil, nil];
        [alert show];
            
        }];
        
    }
}



// 忘记密码 按钮实现
- (void)goToForgetVC:(UIButton * )sender{
    ForgetMMViewController *forgetVC = [[ForgetMMViewController alloc]init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:forgetVC animated:YES];
}
//  手机注册按钮实现
- (void)toRegisterControl:(UIButton *)sender{
    RegistViewController *regVC = [[RegistViewController alloc]init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:regVC animated:YES];
   
}

- (void)diDone:(UITextField *)sender{
//    if (sender.text.length >= 1) {
//        self.loginBt.enabled = YES;
//        self.loginBt.backgroundColor = [UIColor grayColor];
//    }else{
//        return;
//    }
    
}
#pragma  mark UITextFieldDelegate---- 响应方法

- ( BOOL )textFieldShouldReturn:( UITextField *)textField{
    [_phoneTF resignFirstResponder];
    [_mmTF resignFirstResponder];
    [textField resignFirstResponder];
    return  YES;
}
//点击屏幕空白处去掉键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.phoneTF resignFirstResponder];
    [self.mmTF resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (self.mmTF.text.length < 1) {
//        self.loginBt.enabled = NO;
//        self.loginBt.backgroundColor = [UIColor grayColor];
        NSLog(@"123456789");
    }
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
